Skip to main content

ThreeJS

We introduced threeJS to help us create 3D scenes. This section will give a brief introduction to three.js; We're going to start building a scene.

Module import

    import * as THREE from '/three/build/three.module.js';

Create a scenario

In order to be able to actually display anything with three.js, we need three things: the scene, the camera, and the renderer so that we can render the scene with the camera.

const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );

const renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );

Render the scene

We need to create a continuously rendering effect or animation loop to display the individual.

function animate() {
requestAnimationFrame( animate );
renderer.render( scene, camera );
}
animate();

Result

You have now completed your first three.js application. The full code is available below as an editable live example.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>My first three.js app</title>
<style>
body { margin: 0; }
</style>
</head>
<body>
<script type="module">
import * as THREE from '/three/build/three.module.js';
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );

const renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );

const geometry = new THREE.BoxGeometry();
const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
const cube = new THREE.Mesh( geometry, material );
scene.add( cube );

camera.position.z = 5;

function animate() {
requestAnimationFrame( animate );
renderer.render( scene, camera );
};

animate();
</script>
</body>
</html>